#include "mainwindow_utils.h"
#include <QString>
#include <QFileInfo>
char *mystrcopy(const char *str)
{
   char * res = NULL;
   int len = strlen(str);
   res = new char[len + 2];
   strncpy(res, str, strlen(str) + 2);
   res[len + 1] = 0;

   return res;
}

bool str_test(char *str)//detect encoding of str
{
    QString qstr = "";
    QFileInfo finfo;
    qstr = QString::fromAscii(str);
    finfo.setFile(qstr);
    if (finfo.exists())
        return true;

    qstr = QString::fromLatin1(str);
    finfo.setFile(qstr);
    if (finfo.exists())
        return true;

    qstr = QString::fromUtf8(str);
    finfo.setFile(qstr);
    if (finfo.exists())
        return true;

    qstr = QString::fromLocal8Bit(str);
    finfo.setFile(qstr);
    if (finfo.exists())
        return true;

    return false;
}

char *str_decode(QString &str)
{

    char *fnameascii, *fnameutf8, *fnamelocal8bit, *fnamelatin1;
    fnameascii = mystrcopy(str.toAscii().data());
    fnameutf8 = mystrcopy(str.toUtf8().data());
    fnamelocal8bit = mystrcopy(str.toLocal8Bit().data());
    fnamelatin1 = mystrcopy(str.toLatin1().data());
    char *fname = mystrcopy(fnameutf8);

    if (str_test(fnameascii))
        fname = mystrcopy(fnameascii);
    else
        if (str_test(fnameutf8))
            fname = mystrcopy(fnameutf8);
        else
            if (str_test(fnamelocal8bit))
                fname = mystrcopy(fnamelocal8bit);
            else
                if (str_test(fnamelatin1))
                    fname = mystrcopy(fnamelatin1);

    delete [] fnameascii;
    delete [] fnamelatin1;
    delete [] fnamelocal8bit;
    delete [] fnameutf8;
    return fname;
}
